<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '基础信息' },
          { name: 'box-print', title: '打印配置' },
          { name: 'box-code', title: '标签配置' },
          { name: 'box-head', title: '表头配置' },
          { name: 'box-column', title: '列配置' },
          { name: 'box-foot', title: '表尾配置' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <div id="box-base" class="box-title">基础信息</div>
          <customFormItem
            label="所属业务"
            name="busType"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.selectDict.name"
            :config="{dictType: constCommon.dictType.printBusType}"
          />
          <customFormItem
            label="打印类型"
            name="printType"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.selectDict.name"
            :config="{dictType: constCommon.dictType.printType}"
          />

          <div id="box-print" class="box-title">打印配置</div>
          <customFormItem label="主标题" name="title" :parent="_self" :form="form.configJson" />
          <customFormItem label="副标题" name="subTitle" :parent="_self" :form="form.configJson" help="{hospitalName}请领单"/>
          <customFormItem label="显示副标题" name="showSubTitle" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.switch.name"/>
          <customFormItem label="表头带边框" name="flagHeadBorder" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.switch.name"/>
          <customFormItem label="表头带边框" name="flagHeadBorder" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.switch.name"/>
          <customFormItem label="填充空白行" name="fillBlank" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.switch.name"/>
          <customFormItem label="分页格式" name="pageFormat" :parent="_self" :form="form.configJson" />
          <customFormItem label="行高" name="rowHeight" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.inputNumber.name"/>
          <customFormItem label="每页显示标题" name="titleEveryPage" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.switch.name"/>
          <customFormItem label="每页显示表头" name="headEveryPage" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.switch.name"/>
          <customFormItem label="每页显示表尾" name="footEveryPage" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.switch.name"/>
          <customFormItem
            label="打印方向"
            name="printerSelOrient"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.selectStatic.name"
            :config="{options: constCommon.nobusConst.printerSelOrient}"
          />
          <customFormItem label="纸张宽度" name="printerPageWidth" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.inputNumber.name"/>
          <customFormItem label="纸张高度" name="printerPageHeight" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.inputNumber.name"/>
          <customFormItem label="每页行数" name="printerPageSize" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.inputNumber.name"/>
          <customFormItem label="不打印序列号" name="noPrintSeq" :parent="_self" :form="form.configJson" :type="constCommon.formItemType.switch.name"/>
        </template>
      </customForm>

      <div id="box-code" class="box-title">标签配置</div>
      <data-view
        v-show="form.id != null"
        propViewKey="print_field"
        :propInitData="form"
        ref="childDataViewBarCode"
        :propHidePageSearch="true"
        :propHideQueryButton="true"
        :propDisabledActiveNext="true"
        :propAutoFetchData="false"
        :propOptions="getOptions"
        :propParentData="propParent.viewFormData"
        :propPreQueryWrapper="$newWrapper().eq('templateId', form.id).eq('type', type.barcode)"
        :propHideColumns="['summary', 'dict', 'flagLineFeed', 'flagShowNegative', 'flagFontBold', 'flagBreak', 'flagGroup', 'fontSize', 'orderRule']"
        @after-load="afterLoad('childDataViewBarCode')"
        @select-change="rowSelectChange($event, type.barcode, 'childDataViewBarCode')"
      />

      <div id="box-head" class="box-title">表头配置</div>
      <data-view
        v-show="form.id != null"
        propViewKey="print_field"
        :propInitData="form"
        ref="childDataViewHeader"
        :propHidePageSearch="true"
        :propHideQueryButton="true"
        :propAutoFetchData="false"
        :propOptions="getOptions"
        :propParentData="propParent.viewFormData"
        :propPreQueryWrapper="$newWrapper().eq('templateId', form.id).eq('type', type.header)"
        :propHideColumns="['summary', 'flagLineFeed', 'flagFontBold', 'flagBreak', 'flagGroup', 'orderRule']"
        @after-load="afterLoad('childDataViewHeader')"
        @select-change="rowSelectChange($event, type.header, 'childDataViewHeader')"
        :propDisabledActiveNext="true"
      />

      <div id="box-column" class="box-title">列配置</div>
      <data-view
        v-show="form.id != null"
        propViewKey="print_field"
        :propInitData="form"
        ref="childDataViewColumns"
        :propHidePageSearch="true"
        :propHideQueryButton="true"
        :propAutoFetchData="false"
        :propOptions="getOptions"
        :propParentData="propParent.viewFormData"
        :propPreQueryWrapper="$newWrapper().eq('templateId', form.id).eq('type', type.items)"
        :propHideColumns="['flagShareRow', 'shareRow', 'formation']"
        @after-load="afterLoad('childDataViewColumns')"
        @after-save="getColumnWidth"
        @select-change="rowSelectChange($event, type.items, 'childDataViewColumns')"
        :propDisabledActiveNext="true"
      />

      <div id="box-foot" class="box-title">表尾配置</div>
      <data-view
        v-show="form.id != null"
        propViewKey="print_field"
        :propInitData="form"
        ref="childDataViewFoot"
        :propHidePageSearch="true"
        :propHideQueryButton="true"
        :propAutoFetchData="false"
        :propOptions="getOptions"
        :propParentData="propParent.viewFormData"
        :propPreQueryWrapper="$newWrapper().eq('templateId', form.id).eq('type', type.foot)"
        :propHideColumns="['summary', 'flagLineFeed', 'flagFontBold', 'flagBreak', 'flagGroup', 'orderRule', 'flagShareRow', 'shareRow', 'formation']"
        @after-load="afterLoad('childDataViewFoot')"
        @select-change="rowSelectChange($event, type.foot, 'childDataViewFoot')"
        :propDisabledActiveNext="true"
        @edit-input="childDataViewFootRowEditInput"
      />
    </div>
  </div>
</template>

<script>
import FortenPrintForm from '@/components/common/FortenPrintForm.vue'
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {
        configJson: {}
      },
      firstLoad: true,
      type: { //打印的部位
        barcode: 1,
        header: 2,
        items: 3,
        foot: 4
      },
      wholeColumnWidth: 0,
      formColumns: [],
      itemColumns: [],
      dataViewKeys: ['childDataViewBarCode', 'childDataViewHeader', 'childDataViewColumns', 'childDataViewFoot'],
      itemViewKey: 'childDataViewColumns',
      dictTypeList: [],
      preViewForm: null, //预览表单
      preViewList: null, //预览明细
      preViewRefKey: '', //关联主键Id
    }
  },
  methods: {
    getOptions(viewKey, formViewKey) {
      let key = 'field'
      let viewKeyOptions = []
      let params = { viewKey}
      this.$ajax.get('/data-view/find', { params }).then(resp => {
        if (resp.data && resp.data.view) {
          resp.data.view.columns.forEach(column => {
            viewKeyOptions.push({id: column.name, name: column.name + '(' + column.title + ')'})
          })
          viewKeyOptions = viewKeyOptions.sort((c1, c2) => c1.name - c2.name)
          if (formViewKey) {
            this.preViewForm = resp.data.view
            this.dataViewKeys.forEach(item => {
              if (item != this.itemViewKey) {
                this.$refs[item].pushViewKeyOptions(key, viewKeyOptions)
              }
            })
            this.formColumns = resp.data.view.columns
          } else {
            this.preViewList = resp.data.view
            this.$refs[this.itemViewKey].pushViewKeyOptions(key, viewKeyOptions)
            this.itemColumns = resp.data.view.columns
          }
        }
      })
    },
    async preViewPrint() { //打印预览
      if (!this.preViewForm || !this.preViewList) {
        return
      }
      let viewForm = {}
      //获取page的第一条数据
      const params = {
        currentPage: 1,
        rowsPerPage: 10,
        orderString: this.generateOrder()
      }
      await this.$ajax.get(this.preViewForm.listEntry, params).then(resp => {
        viewForm.form = resp.data[0]
      })
      if (!viewForm.form) {
        return
      }

      let param = {
        that: this, //当前调用对象
        isView: true, // true:工作台打印设置
        isOnlyPrintForm: true, // true:工作台打印设置
        printAuto: false, // true:自动打印
        fromConfig: true, // true:来自于打印配置

        configList: [//打印配置，可以多个
          {
            //打印配置
            printBusType: this.form.busType, //打印业务类型，来源print_template.bus_type，同constPrint.busKey

            //主单据数据或者数据查询配置
            formData: viewForm.form, //数据对象
            formDataId: viewForm.form.id,

            //明细网格数据或者数据查询配置
            itemDataQueryWrapper: null, //数据查询参数
            itemDataOrderWrapper: null, //数据排序参数，可以为空
          }
        ]
      }
      global.utilPrint.openFormPrint(param)
    },
    // 生成查询条件
    generateQuery(refKey, pkId) {
      let wrapper = this.$newWrapper().eq(refKey, pkId)
      return JSON.stringify(wrapper.queryConditions)
    },
    // 生成排序条件
    generateOrder() {
      let wrapper = this.$newWrapper()
      wrapper.orderBy('desc', 'id')
      return JSON.stringify(wrapper.orderConditions)
    },
    //下拉列表选择后
    busTypeChange(busType) {
      let refViewKey = this.constPrint.filter(view => view.busKey == busType)
      if (refViewKey != null && refViewKey.length > 0) {
        let selViewKey = refViewKey[0]
        this.$set(this.form, 'dataViewKey', selViewKey.formViewKey)
        this.$set(this.form, 'itemViewKey', selViewKey.itemViewKey)
        this.preViewRefKey = selViewKey.refKey
        this.getOptions(selViewKey.formViewKey, true)
        this.getOptions(selViewKey.itemViewKey, false)
      }
    },
    //当已有数据时，afterLoad来设置Key的Option
    afterLoad(dataViewKey) {
      if (this.form.id && this.firstLoad) {
        this.firstLoad = false
        this.busTypeChange(this.form.busType)
      }
      let key = 'dict'
      this.$refs[dataViewKey].pushViewKeyOptions(key, this.dictTypeList)

      if (dataViewKey == 'childDataViewColumns') {
        this.getColumnWidth()
      }
    },
    getColumnWidth() { //获取总的宽度设定
      this.wholeColumnWidth = 0
      this.$refs.childDataViewColumns && this.$refs.childDataViewColumns.getRows().forEach(row => {
        this.wholeColumnWidth =  this.wholeColumnWidth + +row.width
      })
    },
    //dataView选择事件
    rowSelectChange({row, column}, type, ref) {
      if (!row.templateId) {
        this.$set(row, 'templateId', this.form.id)
        this.$set(row, 'sort', this.$refs[ref].getRows().length * 10)
        this.$set(row, 'width', ref == 'childDataViewColumns' ? 10 : 8)
        this.$set(row, 'summary', 0)
        this.$set(row, 'fontSize', 12)
        this.$set(row, 'flagLineFeed', true) //自动换行，不自动换行的超出部分会自动隐藏。。。
        this.$set(row, 'format', ref == 'childDataViewBarCode' ? 'barcode' : '')
        this.$set(row, 'type', type)
      }
      if (column.property == 'summary') {
        this.$set(row, 'summary', row.summary)
      }
      if (column.property == 'field') {
        let field = 'field'
        let selColumns = this.formColumns.filter(column => column.name == row[field])
        if (selColumns.length == 0) {
          selColumns = this.itemColumns.filter(column => column.name == row[field])
        }
        if (selColumns.length > 0) {
          this.$set(row, 'label', selColumns[0].title)
        }
      }
    },
    childDataViewFootRowEditInput({row, column}) {
      this.$set(row, 'templateId', this.form.id)
    }
  },
  created() {
    let that = this
    this.dictTypeList = this.$store.getters.dictTypeList.map(item => {
      return {id: item.code, name: item.code + '(' + item.name + ')'}
    })
    this.$emit('event-register', {
      validate: callback => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        if (!that.form.id) {
          let configJson = {
            printerPageWidth: 210,
            printerPageHeight: 297,
            printerPageSize: 20,
            dataViewKey: '',
            title: '',
            subTitle: '',
            flagHeadBorder: false,
            showSubTitle: true,
            fillBlank: false,
            pageFormat: '第a页/共b页',
            printerSelOrient: '1',
            rowHeight: 20,
            titleEveryPage: true,
            headEveryPage: true,
            footEveryPage: true
          }
          that.$set(that.form, 'configJson', configJson)
        } else {
          if (!(that.form.configJson instanceof Object)) {
            that.$set(that.form, 'configJson', JSON.parse(that.form.configJson))
          }
          that.busTypeChange(that.form.busType)
          that.dataViewKeys.forEach(item => {
            that.$refs[item].fetchData()
          })
        }
      },
      afterSave: () => {

      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {},
      beforeFlow: flowButtonKey => {
        return true
      },
      afterFlow: flowButtonKey => {},
      beforeClose: () => {
        return true
      },
      async afterClick(button, data, viewForm) {
        let {key: buttonKey} = button
        if (buttonKey == 'preView') {
          await that.preViewPrint()
        }
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object
  },
  components: {FortenPrintForm, customAnchor},
  computed: {
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}
.form-unit {
  line-height: 20px !important;
  padding-bottom: 0px !important;
}
.vxe-grid .vxe-toolbar .vxe-button--wrapper .vxe-button {
  height: 25px !important;
  padding: 3px !important;
}
.el-input__inner {
    height: 26px !important;
    line-height: 26px !important;
}

  .preview-box{

  }
</style>
